package com.linksoul.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;

@Slf4j
@Configuration
@MapperScan(
        basePackages = "com.linksoul.mapper",
        sqlSessionFactoryRef = "linkSoulSqlSessionFactory"
)
public class LinkSoulDataSourceConfig {

    @Primary
    @Bean(name = "linkSoulDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.link-soul")
    public DataSource linkSoulDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "linkSoulSqlSessionFactory")
    public SqlSessionFactory linkSoulSqlSessionFactory(
            @Qualifier("linkSoulDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // 关键配置：启用下划线转驼峰
        org.apache.ibatis.session.Configuration configuration =
                new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true); // ✅ 开启驼峰映射
        // 关键修复点：指定模块化XML路径
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver()
                        .getResources("classpath*:/mappers/soulMbti/*.xml")
        );

        return bean.getObject();
    }
}